#!/usr/bin/env python
# -*- coding: utf-8 -*-

#-*-
# UbiNote - A Lightweight Note-talking Application
#
# Copyright (C) 2006-2009 Shellex <5h3ll3x@gmail.com>
#
# UbiNote is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# UbiNote is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with UbiNote; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA


import sqlite3
import sys
import os.path
class dbmgr:
    conn = None
    create_steps = [
    '''CREATE TABLE "block" ("id" INTEGER PRIMARY KEY  NOT NULL  DEFAULT 0 ,"note_id" INTEGER NOT NULL  DEFAULT 0 ,"content" TEXT, "pos" INTEGER DEFAULT 0)''',
    '''CREATE TABLE "note" ("id" INTEGER PRIMARY KEY  NOT NULL  DEFAULT 0 , "title" VARCHAR(256))''',
    '''CREATE TABLE "tag" ("id" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  DEFAULT 0, "name" VARCHAR(256) NOT NULL , "count" INTEGER DEFAULT 0)''',
    '''CREATE TABLE "tag2block" ("id" INTEGER PRIMARY KEY  AUTOINCREMENT  DEFAULT 0, "tag_id" INTEGER NOT NULL  DEFAULT -1, "block_id" INTEGER NOT NULL  DEFAULT -1)'''
    ]

    @staticmethod
    def create_db(file):
        c = dbmgr.conn.cursor()
        for step in dbmgr.create_steps:
            c.execute(step)
        c.commit()
        c.close()

    @staticmethod
    def attach(file):
        if not os.path.exists(file):
            dbmgr.conn = sqlite3.connect(file)
            dbmgr.create_db(file)
        else:
            dbmgr.conn = sqlite3.connect(file)
        dbmgr.conn.text_factory = str #lambda x: unicode(x, "utf-8", "ignore")


    @staticmethod
    def detach():
        dbmgr.conn.close()

    @staticmethod
    def get_conn():
        return dbmgr.conn
    
    @staticmethod
    def cursor():
        return dbmgr.conn.cursor()

    @staticmethod
    def commit():
        dbmgr.conn.commit()
    
    @staticmethod
    def execute(sql):
        dbmgr.conn.execute(sql)



